import { getToken, removeToken, setToken } from '@/utils/auth'
import { getUserId, getUserInfo, login } from '@/api/user'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    updateToken(state, token) {
      state.token = token
      // cookie存储
      setToken(token)
    },
    // 设置用户信息
    updateUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },

  actions: {
    async  userLogin(context, loginForm) {
      const res = await login(loginForm)
      // 如果正确此处打印
      // console.log(res)
      context.commit('updateToken', res.data)
      return res
    },
    async  getUserPro(context) {
      const res = await getUserInfo()
      // console.log(res) 获取基本资料
      // res.data.userId请求所需要的参数值
      const res2 = await getUserId(res.data.userId)
      // console.log(res2)用户基本信息获取
      context.commit('updateUserInfo', { ...res.data, ...res2.data })
      return { ...res.data, ...res2.data }
    },
    logout(context) {
      context.commit('removeToken')
      context.commit('removeUserInfo')
      resetRouter()
    }

  }
}
